<?php
/**
 * Created by PhpStorm.
 * User: PC
 * Date: 2022-07-15
 * Time: 18:34
 */

namespace ding;

use app\common\BaseLogic;
use app\common\config\logic\ConfigSystem;
use fast\Http;
use think\Exception;

class Ding extends BaseLogic
{

    // 获取token
    public function getAccessToken()
    {
        // 获取钉钉的配置文件
        $systemLogic = new ConfigSystem();
        $config = $systemLogic->getConfigItem("dingding");
        // $config['app_key'] = $config['app_key'] . "100";

        $cacheKey = 'dd-access-token' . $config['app_key'];
        $token = $this->redis->get($cacheKey);

        if (!$token) {
            $url = "https://oapi.dingtalk.com/gettoken?appkey={$config['app_key']}&appsecret={$config['app_secret']}";
            $json = file_get_contents($url);
            $result = json_decode($json, true);
            if ($result['errcode'] == '0') {
                $token = $result['access_token'];
                $this->redis->set($cacheKey, $token, 7000);
            } else {
                throw new Exception($result['errmsg'], $result['errcode']);
            }
        }

        return $token;


    }

    public function getUserIdByMobile($mobile)
    {
        $accessToken = $this->getAccessToken();
        $query = "?access_token=" . $accessToken;
        $url = "https://oapi.dingtalk.com/topapi/v2/user/getbymobile" . $query;

        $formData = [];
        $formData['mobile'] = $mobile;
        $res = Http::post($url, $formData);
        $resp = json_decode($res, 1);
        if ($resp['errcode'] == '0') {
            return $resp['result']['userid'];
        } else {
            throw new Exception($resp['errmsg'], $resp['errcode']);
        }
    }
}